package gd.qaq.blue.bluespick.command;

import com.gmail.filoghost.holographicdisplays.api.Hologram;
import com.gmail.filoghost.holographicdisplays.api.HologramsAPI;
import com.gmail.filoghost.holographicdisplays.api.line.HologramLine;
import gd.qaq.blue.bluespick.BluesPick;
import gd.qaq.blue.bluespick.api.PickAPI;
import gd.qaq.blue.bluespick.dto.AreaData;
import gd.qaq.blue.bluespick.dto.PickBlockData;
import gd.qaq.blue.bluespick.entity.PickHologram;
import gd.qaq.blue.bluespick.listener.AreaListener;
import gd.qaq.blue.bluespick.util.ItemUtil;
import gd.qaq.blue.bluespick.util.area.Area;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.*;

import static gd.qaq.blue.bluespick.BluesPick.*;
import static gd.qaq.blue.bluespick.util.AreaUtil.getCurrentArea;
import static gd.qaq.blue.bluespick.util.ItemUtil.createItem;
import static gd.qaq.blue.bluespick.util.StringUtil.*;
import static gd.qaq.blue.bluespick.util.StringUtil.colorFormat;

public class BluesPickCommands implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (sender instanceof Player) {
            Player player = (Player) sender;
            if (!player.isOp()) {
                return true;
            }
            if (args.length <= 0) {
                return true;
            }
            String action = args[0];
            switch (args.length) {
                case 0:
                    guide((Player) sender);
                    return true;
                case 1:
                    if (action.equalsIgnoreCase("ct")) {
                        String toolID = BluesPick.config.getString("chooseToolID");
                        ItemStack item = createItem(toolID, "&b采集插件选区工具", "&d这是一个选区工具~", "&6作者:blue,qq862899738", "&6插件交流群:&f540900839", "&d&l接插件定制!!");
                        if (item == null) {
                            error(sender, "获取物品失败!");
                            return true;
                        }
                        player.getInventory().addItem(item);
                        success(player, "选区工具已发送至你的背包!");
                        return true;
                    } else if (action.equalsIgnoreCase("pt")) {
                        String toolID = BluesPick.config.getString("pickToolID");
                        ItemStack item = createItem(toolID, "&d采集物设置工具", "&d这是采集物设置工具~");
                        if (item == null) {
                            error(sender, "获取物品失败!");
                            return true;
                        }
                        player.getInventory().addItem(item);
                        success(player, "采集物设置工具已发送至你的背包!");
                        return true;
                    }else if (action.equalsIgnoreCase("et")) {
                        String toolID = BluesPick.config.getString("editToolID");
                        ItemStack item = createItem(toolID, "&a采集物编辑工具", "&a这是采集物编辑工具~","&e左键点击采集物可以编辑采集工具","&e右键点击采集物可以编辑采集掉落物");
                        if (item == null) {
                            error(sender, "获取物品失败!");
                            return true;
                        }
                        player.getInventory().addItem(item);
                        success(player, "采集物设置工具已发送至你的背包!");
                        return true;
                    }else if(action.equalsIgnoreCase("help")){
                        guide((Player) sender);
                        return true;
                    } else if (action.equalsIgnoreCase("reload")) {
                        plugin.reload((Player) sender);
                        return true;
                    }
                    break;
                case 2:
                    if (action.equalsIgnoreCase("create")) {
                        if (!AreaListener.choosingPlayers.containsKey(((Player) sender).getUniqueId().toString())) {
                            error(sender, "你还没有进行选区操作!");
                            return true;
                        }
                        AreaData current = PickAPI.checkInArea(player);
                        if(current!=null){
                            error(sender,"创建失败!因为这里已经有一个名为&e"+current.getAreaName()+"&c的采集区域了!");
                            return true;
                        }
                        String areaName = args[1];
                        Location[] locations = AreaListener.choosingPlayers.get(((Player) sender).getUniqueId().toString());
                        Location minLocation = locations[0];
                        Location maxLocation = locations[1];
                        if (minLocation == null || maxLocation == null) {
                            error(sender, "你还没有完成选区操作!");
                            return true;
                        }
                        Area area = new Area(minLocation, maxLocation);
                        AreaData areaData = new AreaData();
                        areaData.setAreaName(areaName);
                        areaData.setArea(area);
                        if (jdbcUtils.addArea(areaData)) {
                            success(sender, "创建区域成功!区域名为:&e" + areaName);
                            BluesPick.areas.add(areaData);
                        } else {
                            error(sender, "创建区域失败!");
                        }
                        return true;
                    }
                    break;

//              /bp pick set <名称> <采集所需时间> <恢复时间> 设置/创建采集物
                case 5:
                    if (action.equalsIgnoreCase("pick")&&args[1].equalsIgnoreCase("set")) {
                        //检查玩家是否已经选择了一个方块
                        String uuid = player.getUniqueId().toString();
                        Location[] locations = AreaListener.choosingPlayers.get(uuid);
                        if (locations == null || locations[2] == null) {
                            error(sender, "你还没有选择一个方块作为采集物!");
                            return true;
                        }
                        AreaData currentArea = getCurrentArea(locations[2]);
                        if (currentArea == null) {
                            //如果不在区域里，报错
                            error(player, "这里不是一个有效的采集区域!");
                        } else {
                            try {
                                String pickName = colorFormat(args[2]); //采集物名称
                                double pickTime = Double.parseDouble(args[3]);//采集所需时间
                                double replaceTime = Double.parseDouble(args[4]);//恢复时间
                                int typeId = locations[2].getBlock().getTypeId();
                                byte data = locations[2].getBlock().getData();
                                List<Block> blocks = currentArea.getArea().getAllBlocks(typeId, data);
                                List<Location> locations_ = new ArrayList<>();
                                for (Block block : blocks) {
                                    plugin.getLogger().info("目前locations_里有："+Arrays.toString(locations_.toArray()));
                                    for (Location location : locations_) {
                                        plugin.getLogger().info(location.getWorld().getName()+"&&"+
                                                location.getX()+"&&"+location.getY()+"&&"+location.getZ());
                                        if(block.getLocation().getWorld().getName().equals(location.getWorld().getName())
                                                &&block.getLocation().getX()==location.getX()
                                                &&block.getLocation().getY()==location.getY()
                                                &&block.getLocation().getZ()==location.getZ()
                                                ){
                                            //如果发现有两个位置一样的采集物，则不通过
                                            error(player,"采集物设置失败，因为有多个采集物的位置一样，为了防止位置冲突，无法设置，产生该问题的原因可能是因为采集物是不规则的方块(例如：草)");
                                            return true;
                                        }
                                    }
                                    locations_.add(block.getLocation());
                                }
                                if (jdbcUtils.addPick(new PickBlockData(locations[2].getWorld().getName(),locations[2].getX(),locations[2].getY(),locations[2].getZ(),currentArea,pickName,typeId + ":" + data, pickTime, replaceTime, new ArrayList<>(),new ArrayList<>()))) {
                                    success(player, "方块" + typeId + ":" + data + "已被设置为采集方块");
                                    //创建采集物全息提示
                                    for (Block block : blocks) {
                                        Location location = block.getLocation();
                                        Hologram hologram = HologramsAPI.createHologram(plugin, new Location(location.getWorld(),
                                                location.getX() + config.getDouble("hologram.offset.x"),
                                                location.getY() + config.getDouble("hologram.offset.y"),
                                                location.getZ() + config.getDouble("hologram.offset.z")));
                                        hologram.appendTextLine(colorFormat(pickName.replace(";;"," ")+" &7&l||||||||||"));
                                        //把所有的采集物和他的全息图关联起来
                                        PickHologram pickHologram = new PickHologram();
                                        pickHologram.setHologram(hologram);
                                        pickHologram.setBlock(block);
                                        holograms.put(location.getWorld().getName()+"&&"+
                                                location.getX()+"&&"+location.getY()+"&&"+location.getZ(),pickHologram);
                                    }
                                } else {
                                    success(player, "");
                                }
//                        String needItem = args[3];//所需工具
                            } catch (NumberFormatException e) {
                                error(player, "输入参数不是数字!");
                            }
                        }
                        return true;
                    }
                    break;
            }

        }
        error(sender, "输入指令/参数有误!");
        return true;
    }

    private void guide(Player player){
        if (!player.isOp() && !player.hasPermission("bluespick.*")) {
            player.sendMessage(colorFormat("&c你没有权限这么做!"));
            return;
        }
        StringBuilder helpContent = new StringBuilder();
        helpContent.append("&6&l-----------&b&lBluesPick&6&l------------\n");
        helpContent.append("&b(插件指令可以简化为bp)\n");
        helpContent.append("&b/bp ct &e获取采集插件选区工具\n");
        helpContent.append("&b/bp pt &e获取采集物选取工具\n");
        helpContent.append("&b/bp et &e获取采集物编辑工具\n");
        helpContent.append("&b/bp pick set <名称> <采集所需时间> <恢复时间> &e设置/创建采集物\n");
        helpContent.append("&b/bp pick del &e删除所选采集物\n");
        helpContent.append("&b/bp area list &e查看采集区域列表\n");
        helpContent.append("&b/bp area tp <名称> &e传送到采集区域\n");
        helpContent.append("&b/bp area create <名称> &e创建采集区域\n");
        helpContent.append("&b/bp area del <名称> &e删除采集区域\n");
        helpContent.append("&b/bp reload &e重载插件\n");
        helpContent.append("&6&l--------------------------------");
        player.sendMessage(colorFormat(helpContent.toString()));
    }
}
